<template>
  <div style="height: calc( 100vh - 70px)">
    <a-card :title="title">
      <SchemaForm>
        <template #countdown="{ formModel, field }">
          <countDown ref="countdownRest" title="" :countdown="10" format=" D 天 H 时 m 分 s 秒" finishedText="Finished">
            <!-- <template #finish>&lt; FinishedText slot &gt;</template> -->
          </countDown>
        </template>
      </SchemaForm>

      <div style="text-align: center;">
        <Space v-if="receiveShow">
          <AButton color="rgb(64,169,255)" @click="receiveOrder"> 接单 </AButton>
          <AButton color="rgb(64,169,255)" @click="goBack">
            返回
          </AButton>
        </Space>
        <Space v-if="!receiveShow">
          <AButton :color="item.color" v-if="optButtonShow" v-for="(item, index) in optButtons.value"
            @click="handleFunc(item.eventName, item.bindData)" :key="index">{{ item.buttonName }}</AButton>
          <AButton color="rgb(0,225,0)" v-if="jieanButton" @click="openReplyModal"> 结单</AButton>
          <AButton color="rgb(0,225,0)" v-if="duodanweiButton" @click="openMoreSendsModal"> 多单位派单</AButton>
          <AButton color="rgb(64,169,0)" @click="processHisvisibleModel"> 流转记录 </AButton>
          <AButton color="rgb(64,169,255)" @click="goBack">
            返回
          </AButton>
        </Space>
      </div>
    </a-card>
    <DraggableModal v-model:visible="processHisvisible" title="流转历史"
      :body-style="{ maxHeight: '50vh', overflowY: 'auto' }" :centered=false width="60%" :keyboard="false"
      :fullscreen=false :closable=true footer="">
      <processHistory :work-order-number="workOrderObj.workOrderNumber" :instance-id="workOrderObj.instanceId">
      </processHistory>
    </DraggableModal>
  </div>
</template>

<script lang="ts" setup>
import { workorderschemas, sendlastschemas, moresendsschemas } from './formSchemas';
import { Space } from 'ant-design-vue';
import { useForm } from '@/components/core/schema-form';
import { dispatchWorkOrder, getInitWorkOrder, getWorkOrder, sendLastWorkOrder, updateWorkOrder } from '@/api/workorder/order';
import { AButton } from '@/components/basic/button';
import { reactive, ref, onMounted } from 'vue';
import { DraggableModal } from '@/components/core/draggable-modal';
import { useFormModal } from '@/hooks/useModal/useFormModal';
import { addReply, getInitReply } from '@/api/workorder/reply';
import { addVisit, getInitReturnVisit } from '@/api/workorder/visit';
import { addExtension, getInitExtension } from '@/api/workorder/extension';
import { workOrderReplyschemas, uploadFileReplyObject } from '@/views/workorder/reply/formSchemas';
import { returnVisitschemas, uploadFileReturnVisitObject } from '@/views/workorder/visit/formSchemas';
import { uploadAttament } from '../common/common';
import { listAttament } from '@/api/workorder/common/attachment';
import { extensionschemas } from '../extension/formSchemas';
import { useRoute, useRouter } from 'vue-router';
import { useTabsViewStore } from '@/store/modules/tabsView';
import { getTaskListByProcessInstanceId, checkUserIdDoTask, getOptButton } from '@/api/workorder/task';
import { any } from 'vue-types';
import processHistory from '@/views/workorder/task/processHistory/index.vue';
import { getDeptHandledInfoByDeptId } from '@/api/workorder/depthandled'
import countDown from '@/components/basic/countdown/CountDown.vue'

defineOptions({
  name: 'todoWorkOrder',
});
// 工单信息
let workOrderObj = reactive([]);
// 处理工具栏弹框显示
const visible = ref(false);
// 打开回复页面
const [showModal] = useFormModal();
const route = useRoute();
const router = useRouter();

const tabsViewStore = useTabsViewStore();

// 接单按钮
const receiveShow = ref(false)
// 接单按钮
const optButtonShow = ref(false)
// 办理页面按钮隐藏
const isTodoPage = ref(true);
// biaoti
const title = ref('工单信息录入')
// 审批流程数据
let tasks = reactive(any);
// 操作按钮
let optButtons = reactive({ value: [] });
// 正在进行的流程数据
const runningTasks = reactive([]);
// 流转历史是否显示
const processHisvisible = ref(false);
// 倒计时时间
const countdownRest = ref();
const jieanButton = ref(false);
const duodanweiButton = ref(false);


// 代办任务处理详情页面
onMounted(async () => {
  if (route.query.itemId) {
    // 按钮处理业务 1
    isTodoPage.value = false
    title.value = '待办处理'
    workOrderObj = await getWorkOrder(route.query.itemId);
    // countdownRest.value.start(new Date(workOrderObj.expirationTime).getTime())
    tabsViewStore.updateTabTitle(workOrderObj.workOrderNumber);
    // 保存工单信息后数据返填回去
    await dynamicFormRef?.setFieldsValue({
      ...workOrderObj
    });

    if (['1'].indexOf(workOrderObj.workOrderStatus) > -1) {
      receiveShow.value = true
    }
    if (workOrderObj.parentChild == '2' && workOrderObj.workOrderStatus == '14') {
      duodanweiButton.value = true
    }
    // 添加附件列表
    let data = await listAttament({ 'bussId': route.query.itemId });
    let initFileData = [];
    data.forEach((fileData) => {
      initFileData.push({
        uid: fileData.id,
        name: fileData.fileName,
        status: 'done',
      });
    })
    dynamicFormRef?.updateSchema({
      field: 'attament',
      componentProps: {
        fileList: initFileData
      },
    })
    // 禁用表单数据
    disableForm();
    // 加载流程审批信息
    if (workOrderObj.parentChild != '2') {
      await initProcessData();
      optButtonShow.value = await checkUserIdDoTask(runningTasks[0].id)
    }
    if (workOrderObj.workOrderStatus == '14') {
      jieanButton.value = true
    }
  }
});

/**
 *
 * @param methodName 执行方法
 */
const handleFunc = async (methodName, methodParams) => {
  eval(methodName)(methodParams)
}


/**
 * @deprecated 多单位派单选择页面
 */
const openMoreSendsModal = async (methodParams) => {
  const [moreSendsFormRef] = await showModal({
    modalProps: {
      title: `多单位派单`,
      width: '40%',
      cancelText: '关闭',
      onFinish: async (values) => {
        // 赋值工单编号（感觉id比较合适 ~~~）
        values.workOrderNumber = dynamicFormRef?.getFieldsValue().workOrderNumber;
        values = { ...values, ...{ buttonData: methodParams } }
        // 多单位派单
        await dispatchWorkOrder(values);
        // 派单成功后将单据状态改为派单
        await dynamicFormRef?.setFieldsValue({ workOrderStatus: '1' })
        // 禁用表单数据
        disableForm();
        // 关闭工单处理菜单按钮
        visible.value = false;
      },
    },
    formProps: {
      labelWidth: 100,
      schemas: moresendsschemas,
      initialValues: ({
        mainDept: dynamicFormRef?.getFieldsValue().responsibleUnit
      })
    },
  });
};



// 初始化表单内容
const [SchemaForm, dynamicFormRef] = useForm({
  labelWidth: 100,
  schemas: workorderschemas,
  showSubmitButton: false,
  showResetButton: false,
});
// 初始化表单数据信息
initData();
async function initData() {
  const data = await getInitWorkOrder();
  dynamicFormRef?.setFieldsValue({
    workOrderNumber: data.workOrderNumber,
    acceptNumber: data.acceptNumber,
    acceptTime: data.acceptTime,
  });
};



// 加载流程任务数据
async function initProcessData() {
  tasks = await getTaskListByProcessInstanceId({ 'processInstanceId': workOrderObj.instanceId });
  tasks.forEach(task => {
    if (task.result !== 1) { // 只有待处理才需要
      return;
    }
    runningTasks.push({ ...task });
  })
  // 加载操作按钮
  optButtons.value = await getOptButton(runningTasks[0].definitionKey)
}



/**
 * @description 接单处理
 */
const receiveOrder = async () => {
  let param = { "id": workOrderObj.id, "workOrderStatus": "13" }
  await updateWorkOrder(param)
  window.location.reload();
}
/**
 * @description 流转历史表
 */
async function processHisvisibleModel() {
  // 打开操作框选择页面
  processHisvisible.value = true;
}
/**
 * @description 打开新增回复单填报页面
 */
const openReplyModal = async (methodParams) => {
  const [replyFormRef] = await showModal({
    modalProps: {
      title: `添加回复信息`,
      bodyStyle: { height: '48vh' },
      width: '40%',
      cancelText: '关闭',
      onFinish: async (values) => {
        // 赋值工单编号（感觉id比较合适 ~~~）
        values.workOrderNumber = dynamicFormRef?.getFieldsValue().workOrderNumber;
        // 保存回复单信息
        let reply = await addReply(values);
        // 上传附件并保存附件信息
        // 附件上传(回复单)
        await uploadAttament(uploadFileReplyObject.uploadFileList, 'reply', reply.id,);
        // 工单反馈之后跟进工单反馈内容推动流程审批执行
        // 赋值任务单号
        values.taskId = runningTasks[0] ? runningTasks[0].id : "nostart";
        if (['6'].indexOf(workOrderObj.workOrderStatus) > -1) {
          // 流转类型  7 转派回单  8 转派退单
          values.workOrderStatus = values.replyType == '0' ? '7' : '8';
          // 获取上一结点的处理单位
          values.dept = await getDeptIdFromTask();
        } else if (['7', '8', '13', '3', '12'].indexOf(workOrderObj.workOrderStatus) > -1) {
          // 工单反馈
          values.workOrderStatus = values.replyType == '0' ? '2' : '9';
          values.dept = workOrderObj.registrantDeptId;
        } else if (['2', '9', '14'].indexOf(workOrderObj.workOrderStatus) > -1) {
          // 流转类型 5 结案
          values.workOrderStatus = '5'
          // 结案(不需要部门为了不报错  改为单据申请人坐在部门)
          values.dept = workOrderObj.registrantDeptId;
        }
        values = { ...values, ...{ buttonData: methodParams } }

        // 工单转派
        await sendLastWorkOrder(values);
        // 更改工单状态
        await dynamicFormRef?.setFieldsValue({ workOrderStatus: values.workOrderStatus })
        // 关闭工单处理菜单按钮
        visible.value = false;
        window.location.reload();
      },
    },
    formProps: {
      labelWidth: 100,
      schemas: workOrderReplyschemas,
    },
  });
  // 初始化回复单基本信息
  const data = await getInitReply();
  const deptHandled = await getDeptHandledInfoByDeptId(data.sysOrg.id)
  replyFormRef?.setFieldsValue({
    replyNo: data.replyNo,
    replyerId: data.sysOrg.id,
    replyer: data.sysOrg.name,
    handledBy: deptHandled?.name,
    contactNumber: deptHandled?.telephone,
    handledId: deptHandled?.id
  });
};

/**
 * @description 根据流程流转信息获取上一步审批单位的部门id
 */
const getDeptIdFromTask = async () => {
  return tasks.length >= 2 ? tasks[1].todoDeptId : '';
}

const goBack = async () => {
  router.go(-1)
}

/**
 * @description 打开新增回访单填报页面
 */
const openReturnVisitModal = async () => {
  const [returnVisitFormRef] = await showModal({
    modalProps: {
      title: `添加回访信息`,
      width: '40%',
      bodyStyle: { height: '54vh' },
      cancelText: '关闭',
      onFinish: async (values) => {
        // 赋值工单编号（感觉id比较合适 ~~~）
        values.workOrderNumber = dynamicFormRef?.getFieldsValue().workOrderNumber;
        // 保存回访单信息
        let visit = await addVisit(values);
        // 上传附件并保存附件信息
        // 附件上传(回复单)
        await uploadAttament(uploadFileReturnVisitObject.uploadFileList, 'visit', visit.id);
        // 关闭工单处理菜单按钮
        visible.value = false;
        window.location.reload();

      },
    },
    formProps: {
      labelWidth: 100,
      schemas: returnVisitschemas,
    },
  });
  // 初始化回访单基本信息
  const data = await getInitReturnVisit();
  returnVisitFormRef?.setFieldsValue({
    returnVisitNo: data.returnVisitNo,
    returnTime: data.serviceTime,
    filledTime: data.serviceTime,
    filledBy: data.userName,
    returnVisitors: data.userName,
    citizenCall: dynamicFormRef?.getFieldsValue().contactsInfo
  });
};

/**
 * @description 打开新增延期申请单填报页面
 */
const openExtensionModal = async () => {
  const [returnExtensionFormRef] = await showModal({
    modalProps: {
      title: `添加延期申请单`,
      width: '40%',
      cancelText: '关闭',
      okText: '提交',
      onFinish: async (values) => {
        // 赋值工单编号（感觉id比较合适 ~~~）
        values.workOrderNumber = dynamicFormRef?.getFieldsValue().workOrderNumber;
        // 保存回访单信息
        await addExtension(values);
        // 关闭工单处理菜单按钮
        visible.value = false;
        window.location.reload();
      },
    },
    formProps: {
      labelWidth: 100,
      schemas: extensionschemas,
    },
  });
  // 初始化延期申请单基本信息
  const data = await getInitExtension();
  returnExtensionFormRef?.setFieldsValue({
    filledTime: data.filledTime,
    extensionNo: data.extensionNo,
    filledBy: data.filledBy,
    expirationTime: workOrderObj.expirationTime
  });
};


/**
 * @deprecated 转派下级单位页面
 */
const openSendLastModal = async (methodParams) => {
  const [sendLastFormRef] = await showModal({
    modalProps: {
      title: `工单转派`,
      width: '40%',
      bodyStyle: { height: '10vh' },
      cancelText: '关闭',
      onFinish: async (values) => {
        // 赋值工单编号（感觉id比较合适 ~~~）
        values.workOrderNumber = dynamicFormRef?.getFieldsValue().workOrderNumber;
        // 赋值任务单号
        values.taskId = runningTasks[0].id;
        values.definitionKey = runningTasks[0].definitionKey;

        // 流转类型  6:转派下级单位
        if (['2', '9'].indexOf(workOrderObj.workOrderStatus) > -1) {
          values.workOrderStatus = '3'
        }
        if (['13', '12'].indexOf(workOrderObj.workOrderStatus) > -1) {
          values.workOrderStatus = '6'
        }
        values = { ...values, ...{ buttonData: methodParams } }
        // 工单转派
        await sendLastWorkOrder(values);
        // 派单成功后将单据状态改为
        await dynamicFormRef?.setFieldsValue({ workOrderStatus: values.workOrderStatus })
        // 禁用表单数据
        disableForm();
        // 关闭工单处理菜单按钮
        visible.value = false;
        window.location.reload();
      },
    },
    formProps: {
      labelWidth: 100,
      schemas: sendlastschemas,
      initialValues: ({
        mainDept: dynamicFormRef?.getFieldsValue().responsibleUnit,
        workOrderStatus: dynamicFormRef?.getFieldsValue().workOrderStatus
      })
    },
  });
};

/**
 * @description 再派单
 */
const againSendLastModel = async (methodParams) => {
  let params = {};
  // 赋值工单编号（感觉id比较合适 ~~~）
  params.workOrderNumber = workOrderObj.workOrderNumber;
  // 赋值任务单号
  params.taskId = runningTasks[0].id;
  // 流转类型 12 再派单
  params.workOrderStatus = '12'
  // 再派单(责任单位)
  params.dept = workOrderObj.responsibleUnit;
  // 再派单
  params = { ...params, ...{ buttonData: methodParams } }
  await sendLastWorkOrder(params);
  // 派单成功后将单据状态改为
  await dynamicFormRef?.setFieldsValue({ workOrderStatus: params.workOrderStatus })
  // 关闭工单处理菜单按钮
  visible.value = false;
  window.location.reload();
}

// 禁用表单
function disableForm() {
  dynamicFormRef?.setSchemaFormProps({
    disabled: true,
    requiredMark: false,
  });
}


</script>
<style lang="less">
  input,.ant-select-selection-item,textarea{
    color: black !important;
  }
  .ant-radio-disabled+span{
    color: black !important;
    cursor:text !important;
  }
</style>